package com.whut.utils;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.whut.model.Prefixsystem;
import com.whut.model.Problemdescription;
import org.apache.poi.hssf.usermodel.*;
import org.apache.poi.ss.usermodel.HorizontalAlignment;
import org.apache.poi.ss.usermodel.VerticalAlignment;
import org.apache.poi.ss.util.CellRangeAddress;
import org.apache.tools.zip.ZipEntry;
import org.apache.tools.zip.ZipFile;
import org.apache.tools.zip.ZipOutputStream;
import org.springframework.util.ResourceUtils;
import org.apache.commons.io.FileUtils;

import javax.persistence.criteria.CriteriaBuilder;
import java.io.*;
import java.util.Enumeration;
import java.util.Iterator;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import static ch.qos.logback.core.rolling.helper.DateTokenConverter.DEFAULT_DATE_PATTERN;

public class FileUtil {

    private static final int  BUFFER_SIZE = 2 * 1024;

    /** 绝对路径 **/
    private static String absolutePath = "";

    /** 静态目录 **/
    private static String staticDir = "static";

    /** 文件存放的目录 **/
    private static String fileDir = "upload/";

    public static String upload(InputStream inputStream,String path,String fileName){
        //第一次会创建文件夹
        createDirIfNotExists();

        String resultPath = fileDir + path + fileName;

        //存文件
        File uploadFile = new File(absolutePath,resultPath);
        try{
            FileUtils.copyInputStreamToFile(inputStream,uploadFile);
        }catch (IOException io){
            io.printStackTrace();
            return null;
        }
        return absolutePath+"/"+fileDir+path;
    }

    /**
     * 创建文件夹路径
     */
    private static void createDirIfNotExists() {
        if (!absolutePath.isEmpty()) {return;}

        //获取根目录
        File file = null;
        file = new File(getServerFolderPath());

        if(!file.exists()) {
            file = new File("");
        }

        absolutePath = file.getAbsolutePath();

        File upload = new File(absolutePath, fileDir);
        if(!upload.exists()) {
            upload.mkdirs();
        }
    }


    /**
     *解压zip文件
     *@date: 2019/5/24 23:17
    */
    public static void unZipFiles(File zipFile,String descDir,String newFileName)throws IOException {

        String s = null;
        boolean first = true;
        File pathFile = new File(descDir);

        if (!pathFile.exists()) {
            pathFile.mkdirs();
        }
        /*
            不能使用UTF-8
         */
        ZipFile zip = new ZipFile(zipFile, "GBK");
        for (Enumeration entries = zip.getEntries(); entries.hasMoreElements(); ) {
            ZipEntry entry = (ZipEntry) entries.nextElement();
            String zipEntryName = entry.getName();
            InputStream in = zip.getInputStream(entry);
            String outPath = (descDir + zipEntryName).replaceAll("\\*", "/");
            //判断路径是否存在,不存在则创建文件路径
            File file = new File(outPath.substring(0, outPath.lastIndexOf('/')));
            if (!file.exists()) {
                if(first){
                    first = false;
                    s = zipEntryName.split("/")[0];
                }
                file.mkdirs();
            }
            //判断文件全路径是否为文件夹,如果是上面已经上传,不需要解压
            if (new File(outPath).isDirectory()) {
                continue;
            }
            //输出文件路径信息
//            System.out.println(outPath);
            OutputStream out = new FileOutputStream(outPath);
            byte[] buf1 = new byte[1024];
            int len;
            while ((len = in.read(buf1)) > 0) {
                out.write(buf1, 0, len);
            }
            in.close();
            out.close();

        }
        File f = new File(descDir+s);
        f.renameTo(new File(descDir+newFileName));
    }

    public static String getServerFolderPath(){
        //TODO 如果放到服务器根目录，将不会有war包名，应该直接用WEB-INF来匹配
        String oldPath = "";
        try{
            oldPath = ResourceUtils.getURL("classpath:").getPath();
            System.out.println(oldPath);
        }catch (FileNotFoundException e){
            e.printStackTrace();
        }
        String regex = ".*ROOT";
        Pattern pattern = Pattern.compile(regex);
        Matcher matcher = pattern.matcher(oldPath);
        String path = "";
        if(matcher.find()){
            for(int i=0; i<=matcher.groupCount(); i++){
                System.out.println(i+":"+matcher.group(i));
                path = matcher.group(i);
            }
        }
        System.out.println("PPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPP：：：：：：：：：：："+path);
        if(path.equals("")||path==null){
            path="D:\\whutServer\\apache-tomcat-8.5.41\\webapps\\ROOT";
        }
        return path;
    }
    public static void exportMidExcel(Map<String, String> headMap, JSONArray jsonArray, OutputStream out) {
        // 声明一个工作薄
        HSSFWorkbook workbook = new HSSFWorkbook();
        workbook.createInformationProperties();
        workbook.getDocumentSummaryInformation().setCompany("WHUT");
        /*SummaryInformation si = workbook.getSummaryInformation();
        si.setAuthor("YQF");  //填加xls文件作者信息
        si.setApplicationName("导出程序"); //填加xls文件创建程序信息
        si.setLastAuthor("YQF"); //填加xls文件最后保存者信息
        si.setComments("YQF is a programmer!"); //填加xls文件作者信息
        si.setTitle("POI导出Excel"); //填加xls文件标题信息
        si.setSubject("POI导出Excel");//填加文件主题信息
        si.setCreateDateTime(new Date());

        HSSFFont font = workbook.createFont();
        font.setFontName("宋体");
        font.setFontHeightInPoints((short)12);			//设置字体

        HSSFCellStyle cell_style = workbook.createCellStyle();	//通用
        cell_style.setAlignment(HorizontalAlignment.CENTER);		//水平居中
        cell_style.setVerticalAlignment(VerticalAlignment.CENTER);	//垂直居中
        cell_style.setFont(font);
        cell_style.setBorderBottom(BorderStyle.THIN);			//边框
        cell_style.setBorderLeft(BorderStyle.THIN);
        cell_style.setBorderRight(BorderStyle.THIN);
        cell_style.setBorderTop(BorderStyle.THIN);

        HSSFFont font2 = workbook.createFont();
        font2.setFontName("宋体");
        font2.setFontHeightInPoints((short)48);			//设置字体
        font2.setBold(true);									//加粗

        HSSFCellStyle cell_item = workbook.createCellStyle();	//检查分项
        cell_item.setAlignment(HorizontalAlignment.CENTER);		//水平居中
        cell_item.setVerticalAlignment(VerticalAlignment.CENTER);	//垂直居中
        cell_item.setFont(font2);
        cell_item.setBorderBottom(BorderStyle.THIN);			//边框
        cell_item.setBorderLeft(BorderStyle.THIN);
        cell_item.setBorderRight(BorderStyle.THIN);
        cell_item.setBorderTop(BorderStyle.THIN);
        cell_item.setWrapText(true);						//自动换行


        HSSFCellStyle cell_pro = cell_style;		//检查项目
        cell_pro.setWrapText(true);*/
        int[] arrColWidth = new int[headMap.size()];
        String[] headers = new String[headMap.size()];
        String[] headers_name = new String[headMap.size()];
        int ii = 0;
        for(Iterator<String> iterator = headMap.keySet().iterator(); iterator.hasNext();) {
            String key = iterator.next();
            headers[ii] = key;                      //英文名（key）
            headers_name[ii] = headMap.get(key);    //中文名
            arrColWidth[ii++] = headMap.get(key).getBytes().length;
        }

        HSSFSheet sheet = workbook.createSheet();
        workbook.setSheetName(0,"Sheet1");
        HSSFRow titleRow = sheet.createRow(0);  //标题
        for(int i = 0;i < headers.length;i++) {
            titleRow.setHeightInPoints(20);			//设置行高20px
            HSSFCell cell = titleRow.createCell(i);
            cell.setCellValue(headers_name[i]);
            int width = arrColWidth[i]*256 < 2000 ? 2000:arrColWidth[i]*256;
            sheet.setColumnWidth(i, width);
        }
        for (int index = 0;index < jsonArray.size();index++) {      //行
            JSONObject jsonObject = (JSONObject) JSONObject.toJSON(jsonArray.get(index));
            int row_index = index+1;
            HSSFRow dataRow = sheet.createRow(row_index);
            dataRow.createCell(0).setCellValue(row_index);    //编号列0
            for(int col = 1;col < headers.length; col++){       //列
                HSSFCell cell = dataRow.createCell(col);
                Object object = jsonObject.get(headers[col]);
                if(object == null)
                    continue;
                switch (col){
                    case 1:     //参数名称列
                        cell.setCellValue(object.toString());
                        break;
                    case 5:
                        int temp_int = Integer.valueOf(object.toString().replace("%",""));
                        cell.setCellValue(temp_int/100.0);
                        HSSFCellStyle cellStyle = workbook.createCellStyle();
                        cellStyle.setDataFormat(HSSFDataFormat.getBuiltinFormat("0%"));
                        cell.setCellStyle(cellStyle);
                        break;
                    default:
                        cell.setCellValue(Integer.valueOf(object.toString()));
                }
            }

        }
        try {
            workbook.write(out);
            workbook.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }


    public static void exportLastExcel(Map<String, String> headMap, JSONArray jsonArray, OutputStream out) {
        // 声明一个工作薄
        HSSFWorkbook workbook = new HSSFWorkbook();
        workbook.createInformationProperties();
        workbook.getDocumentSummaryInformation().setCompany("WHUT");

        String[] headers = new String[headMap.size()];
        String[] headers_name = new String[headMap.size()];
        int ii = 0;
        for(Iterator<String> iterator = headMap.keySet().iterator(); iterator.hasNext();) {
            String key = iterator.next();
            headers[ii] = key;                      //英文名（key）
            headers_name[ii] = headMap.get(key);    //中文名
            ii++;
        }

        HSSFCellStyle mulRow = workbook.createCellStyle();
        mulRow.setWrapText(true);
        mulRow.setAlignment(HorizontalAlignment.CENTER);		//水平居中
        mulRow.setVerticalAlignment(VerticalAlignment.CENTER);	//垂直居中

        HSSFSheet sheet = workbook.createSheet();
        workbook.setSheetName(0,"Sheet1");
        HSSFRow titleRow = sheet.createRow(0);  //标题
        for(int i = 0;i < headers.length;i++) {
            titleRow.setHeightInPoints(20);			//设置行高20px
            HSSFCell cell = titleRow.createCell(i);
            cell.setCellValue(headers_name[i]);
            sheet.addMergedRegion(new CellRangeAddress(0,1,i,i));   //合并标题
        }
        for (int index = 0;index < jsonArray.size();index++) {      //行
            JSONObject jsonObject = (JSONObject) JSONObject.toJSON(jsonArray.get(index));
            int row_index = index+2;
            HSSFRow dataRow = sheet.createRow(row_index);
            dataRow.createCell(0).setCellValue(row_index-1);    //编号列0
            for(int col = 1;col <= 3; col++){       //问题描述、规范与条款、问题数量（性质）
                HSSFCell cell = dataRow.createCell(col);
                Object object = jsonObject.get(headers[col]);
                if(object == null)
                    continue;
                String s = object.toString();
                if(s.contains(";")){
                    s = s.replace(";","\r\n");
                    cell.setCellStyle(mulRow);
                    cell.setCellValue(new HSSFRichTextString(s));
                }else {
                    cell.setCellValue(object.toString());
                }
            }
            for(int col = 4;col <= 6;col++){        //扣除分数、特征值、附加扣分
                HSSFCell cell = dataRow.createCell(col);
                Object object = jsonObject.get(headers[col]);
                if(object == null)
                    continue;
                String s = object.toString();
                if(s.contains(";")){
                    s = s.replace(";","\r\n");
                    cell.setCellStyle(mulRow);
                    cell.setCellValue(new HSSFRichTextString(s));
                }else {
//                    System.out.println(object.toString());
                    String str = object.toString().trim();
                    String regex = "\\.";
                    Pattern pattern = Pattern.compile(regex);
                    Matcher matcher = pattern.matcher(str);
                    boolean rs = matcher.matches();
                    if(rs)
                        cell.setCellValue(Double.valueOf(str));
                    else
                        cell.setCellValue(Integer.valueOf(str));
                }
            }
            Problemdescription problemdescription = (Problemdescription)jsonArray.get(index);
            JSONArray ja = JSONArray.parseArray(problemdescription.getSuggestion());
            for(int col = 0;col < ja.size();col++){
                dataRow.createCell(col+7).setCellValue(ja.getString(col));
            }

        }
        for (int i = 0; i < headers.length; i++) {
            sheet.autoSizeColumn(i);
        }
        try {
            workbook.write(out);
            workbook.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }


    /**
     * 压缩成ZIP 方法1
     * @param srcDir 压缩文件夹路径
     * @param out    压缩文件输出流
     * @param KeepDirStructure  是否保留原来的目录结构,true:保留目录结构;
     *                          false:所有文件跑到压缩包根目录下(注意：不保留目录结构可能会出现同名文件,会压缩失败)
     * @throws RuntimeException 压缩失败会抛出运行时异常
     */
    public static void toZip(String srcDir, OutputStream out, boolean KeepDirStructure)
            throws RuntimeException{

        long start = System.currentTimeMillis();
        ZipOutputStream zos = null;

        try {
            zos = new ZipOutputStream(out);
            File sourceFile = new File(srcDir);
            compress(sourceFile,zos,sourceFile.getName(),KeepDirStructure);
            long end = System.currentTimeMillis();
            System.out.println("压缩完成，耗时：" + (end - start) +" ms");
        } catch (Exception e) {
            throw new RuntimeException("zip error from ZipUtils",e);
        }finally{
            if(zos != null){
                try {
                    zos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }

    }


    /**
     * 递归压缩方法
     * @param sourceFile 源文件
     * @param zos        zip输出流
     * @param name       压缩后的名称
     * @param KeepDirStructure  是否保留原来的目录结构,true:保留目录结构;
     *                          false:所有文件跑到压缩包根目录下(注意：不保留目录结构可能会出现同名文件,会压缩失败)
     * @throws Exception
     */
    private static void compress(File sourceFile, ZipOutputStream zos, String name,
                                 boolean KeepDirStructure) throws Exception{
        byte[] buf = new byte[BUFFER_SIZE];
        if(sourceFile.isFile()){
            // 向zip输出流中添加一个zip实体，构造器中name为zip实体的文件的名字
            zos.putNextEntry(new ZipEntry(name));
            // copy文件到zip输出流中
            int len;
            FileInputStream in = new FileInputStream(sourceFile);
            while ((len = in.read(buf)) != -1){
                zos.write(buf, 0, len);
            }
            // Complete the entry
            zos.closeEntry();
            in.close();
        } else {
            File[] listFiles = sourceFile.listFiles();
            if(listFiles == null || listFiles.length == 0){
                // 需要保留原来的文件结构时,需要对空文件夹进行处理
                if(KeepDirStructure){
                    // 空文件夹的处理
                    zos.putNextEntry(new ZipEntry(name + "/"));
                    // 没有文件，不需要文件的copy
                    zos.closeEntry();
                }
            }else {
                for (File file : listFiles) {
                    // 判断是否需要保留原来的文件结构
                    if (KeepDirStructure) {
                        // 注意：file.getName()前面需要带上父文件夹的名字加一斜杠,
                        // 不然最后压缩包中就不能保留原来的文件结构,即：所有文件都跑到压缩包根目录下了
                        compress(file, zos, name + "/" + file.getName(),KeepDirStructure);
                    } else {
                        compress(file, zos, file.getName(),KeepDirStructure);
                    }
                }
            }
        }
    }
}
